const {ListNode, getListNodeFromArray, getArrayFromListNode, logList} = require('../../utils/list.js')

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode} 
 */
const addTwoNumbers = function (l1, l2) {
  let head = null, tail = null
  let carry = 0
  while (l1 || l2) {
    let n1 = l1 ? l1.val : 0
    let n2 = l2 ? l2.val : 0
    let sum = n1 + n2 + carry
    if (!head) {
      head = tail = new ListNode(sum % 10)
    } else {
      tail.next = new ListNode(sum % 10)
      tail = tail.next
    }
    carry = Math.floor(sum / 10)
    if (l1) {
      l1 = l1.next
    }
    if (l2) {
      l2 = l2.next
    }
  }
  if (carry > 0) {
    tail.next = new ListNode(carry)
  }
  return head
}

logList(addTwoNumbers(getListNodeFromArray([2,4,3]), getListNodeFromArray([5,6,7,9])))
